﻿using System;
using WFC.BL.DomainModels;
using WFC.BL.Interfaces.DomainModels;
using WFC.BL.Interfaces.Enumerations;
using WFC.BL.Interfaces.Repositories;
using WFC.BL.Interfaces.Utilities;
using WFC.BL.Utilities;
using WFC.DAL.Interfaces.PersistentStorage;
using WFC.DAL.PersistentStorage;

namespace WFC.BL.Repositories
{
    public class RepositoryFacade : IRepositoryFacade
    {

        public IDataService Service { get; set; }
        public IUtilityService Utility { get; set; }

        /// <summary>
        /// Default constructor
        /// </summary>
        public RepositoryFacade()
        {
            Service = new DataService();
            Utility = new UtilityService();
        }

        #region IContentMaintainableRepository Members

        public int InsertContents(CmsPageMode cmsPageMode, string htmlContent, int createdBy)
        {
            string html = Utility.HtmlOptimizer(htmlContent);

            var dt = Service.InsertContents(cmsPageMode, html, createdBy).Tables[0];
            return Convert.ToInt32(dt.Rows[0][0]);
        }

        public IContentMaintainable ReadContentsById(int contentId)
        {
            var dt = Service.ReadContentsById(contentId).Tables[0];
            return Utility.MapDataRowToEntity<Content>(dt.Rows[0]);
        }

        public bool UpdateContents(IContentMaintainable content)
        {
            string html = Utility.HtmlOptimizer(content.HtmlContent);
            content.HtmlContent = html;

            var dt = Service.UpdateContents(content).Tables[0];
            return (dt.Rows[0][0] is DBNull);
        }

        public bool DeleteContents(int contentId)
        {
            var dt = Service.DeleteContents(contentId).Tables[0];
            return (dt.Rows[0][0] is DBNull);
        }

        #endregion

        #region IPostableRepository Members

        public int InsertPosts(string title, string htmlContent, string shortDescription, string tags, int createdBy)
        {
            string html = Utility.HtmlOptimizer(htmlContent);

            var dt = Service.InsertPosts(title, html, shortDescription, tags, createdBy).Tables[0];
            return Convert.ToInt32(dt.Rows[0][0]);
        }

        public IPostable ReadPostsById(int postId)
        {
            var dt = Service.ReadPostsById(postId).Tables[0];
            return Utility.MapDataRowToEntity<Post>(dt.Rows[0]);
        }

        public bool UpdatePosts(IPostable post)
        {
            string html = Utility.HtmlOptimizer(post.HtmlContent);
            post.HtmlContent = html;

            var dt = Service.UpdatePosts(post).Tables[0];
            return (dt.Rows[0][0] is DBNull);
        }

        public bool DeletePosts(int postId)
        {
            var dt = Service.DeletePosts(postId).Tables[0];
            return (dt.Rows[0][0] is DBNull);
        }

        #endregion

    }
}
